package pers.lxl.design.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @describe: 一个家庭中成员按能力(不平分)(同时)来数1亿粒米(使用fork - join模式)
 * @author: lxl
 * @date: 2018/10/21 19:49
 * @version: v1.0
 */
public class TogetherCounter implements Counter {
    private static final int THRESHOLD = 3000;
    private int familyNumber;
    private ForkJoinPool pool;

    public TogetherCounter(int familyNumber) {
        this.familyNumber = familyNumber;
        this.pool = new ForkJoinPool(this.familyNumber);
    }

    @Override
    public long count(double[] riceArray) {
        return pool.invoke(new CounterRiceTask(riceArray, 0, riceArray.length - 1));
    }

    private static class CounterRiceTask extends RecursiveTask<Long> {
        private double[] riceArray;
        private int from;
        private int to;

        public CounterRiceTask(double[] riceArray, int from, int to) {
            this.riceArray = riceArray;
            this.from = from;
            this.to = to;
        }


        @Override
        protected Long compute() {
            long total = 0L;

            if (to - from <= THRESHOLD) {
                for (int i = from; i <= to; i++) {
                    if (riceArray[i] == 1) {
                        total += 1;
                    }
                }
                return total;
            } else {
                int mid = (from + to) / 2;
                CounterRiceTask left = new CounterRiceTask(riceArray, from, mid);
                left.fork();

                CounterRiceTask right = new CounterRiceTask(riceArray, mid + 1, to);
                right.fork();

                return left.join() + right.join();
            }
        }
    }
}
